/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FiltersPanel.java
 *
 * Created on Apr 21, 2010, 11:21:45 AM
 */

package tp_imag.gui.filters;

import ij.ImagePlus;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import tp_imag.gui.components.JImagePanel;
import tp_imag.model.ActualImage;
import tp_imag.model.DifuminadoFilter;
import tp_imag.model.Filter;
import tp_imag.model.PasoBajoFilter;
import tp_imag.model.RealceFilter;
import tp_imag.service.ImageProcessor;
import tp_imag.service.ServiceFactory;

/**
 *
 * @author gdenari
 */
public class FiltersPanel extends javax.swing.JPanel {

    private BufferedImage loadImg;
    private final static String REALCE = "Realce";
    private final static String PASA_BAJO = "Pasa Bajo";
    private final static String DIFUMINADO = "Difuminado";

    private ImageProcessor serv = ServiceFactory.getInstance().getImageProcessorService();
    

    /** Creates new form FiltersPanel */
    public FiltersPanel() {
        initComponents();
        initComboFilters();

        jListFiltros.setModel(new DefaultListModel());
    }

    public void initComboFilters() {
        jComboBoxFiltro.addItem(REALCE);
        jComboBoxFiltro.addItem(PASA_BAJO);
        jComboBoxFiltro.addItem(DIFUMINADO);
        
    }

    public void loadScreen(ImagePlus newImage) {
        loadImage(newImage);

        showOriginalImg();
        showFilteredImg();
        showBinImg();
        
    }

    public void refreshImages() {

        showFilteredImg();
        showBinImg();

        packFrame();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanelOriginal = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jListFiltros = new javax.swing.JList();
        jButtonEliminar = new javax.swing.JButton();
        jButtonAgregar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jComboBoxFiltro = new javax.swing.JComboBox();
        jTextFieldIntensidad = new javax.swing.JTextField();
        jPanel4 = new javax.swing.JPanel();
        jPanelFiltrada = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jPanelBinarizada = new javax.swing.JPanel();

        setName("Form"); // NOI18N
        setLayout(new java.awt.GridLayout(2, 2));

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(FiltersPanel.class);
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel2.border.title"))); // NOI18N
        jPanel2.setName("jPanel2"); // NOI18N

        jPanelOriginal.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jPanelOriginal.setName("jPanelOriginal"); // NOI18N

        javax.swing.GroupLayout jPanelOriginalLayout = new javax.swing.GroupLayout(jPanelOriginal);
        jPanelOriginal.setLayout(jPanelOriginalLayout);
        jPanelOriginalLayout.setHorizontalGroup(
            jPanelOriginalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 312, Short.MAX_VALUE)
        );
        jPanelOriginalLayout.setVerticalGroup(
            jPanelOriginalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 202, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelOriginal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelOriginal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        add(jPanel2);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jListFiltros.setName("jListFiltros"); // NOI18N
        jScrollPane1.setViewportView(jListFiltros);

        jButtonEliminar.setText(resourceMap.getString("jButtonEliminar.text")); // NOI18N
        jButtonEliminar.setName("jButtonEliminar"); // NOI18N
        jButtonEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEliminarActionPerformed(evt);
            }
        });

        jButtonAgregar.setText(resourceMap.getString("jButtonAgregar.text")); // NOI18N
        jButtonAgregar.setName("jButtonAgregar"); // NOI18N
        jButtonAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAgregarActionPerformed(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jComboBoxFiltro.setName("jComboBoxFiltro"); // NOI18N

        jTextFieldIntensidad.setText(resourceMap.getString("jTextFieldIntensidad.text")); // NOI18N
        jTextFieldIntensidad.setName("jTextFieldIntensidad"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jButtonAgregar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonEliminar))
                            .addComponent(jComboBoxFiltro, 0, 226, Short.MAX_VALUE)
                            .addComponent(jTextFieldIntensidad, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jComboBoxFiltro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldIntensidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButtonAgregar)
                    .addComponent(jButtonEliminar))
                .addContainerGap())
        );

        add(jPanel1);

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel4.border.title"))); // NOI18N
        jPanel4.setName("jPanel4"); // NOI18N

        jPanelFiltrada.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jPanelFiltrada.setName("jPanelFiltrada"); // NOI18N

        javax.swing.GroupLayout jPanelFiltradaLayout = new javax.swing.GroupLayout(jPanelFiltrada);
        jPanelFiltrada.setLayout(jPanelFiltradaLayout);
        jPanelFiltradaLayout.setHorizontalGroup(
            jPanelFiltradaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 312, Short.MAX_VALUE)
        );
        jPanelFiltradaLayout.setVerticalGroup(
            jPanelFiltradaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 202, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelFiltrada, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelFiltrada, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        add(jPanel4);

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel3.border.title"))); // NOI18N
        jPanel3.setName("jPanel3"); // NOI18N

        jPanelBinarizada.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jPanelBinarizada.setName("jPanelBinarizada"); // NOI18N

        javax.swing.GroupLayout jPanelBinarizadaLayout = new javax.swing.GroupLayout(jPanelBinarizada);
        jPanelBinarizada.setLayout(jPanelBinarizadaLayout);
        jPanelBinarizadaLayout.setHorizontalGroup(
            jPanelBinarizadaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 312, Short.MAX_VALUE)
        );
        jPanelBinarizadaLayout.setVerticalGroup(
            jPanelBinarizadaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 202, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelBinarizada, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelBinarizada, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        add(jPanel3);
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAgregarActionPerformed
        int intensidad;

        try {
            intensidad = Integer.parseInt(jTextFieldIntensidad.getText());
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "Debe ingresar un valor numérico", "Filtros", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        DefaultListModel model = (DefaultListModel) jListFiltros.getModel();

        if (jComboBoxFiltro.getSelectedItem().equals(DIFUMINADO)) {
            model.addElement((Filter)new DifuminadoFilter(intensidad));
        } else if (jComboBoxFiltro.getSelectedItem().equals(REALCE)) {
            model.addElement((Filter)new RealceFilter(intensidad));
        } else {
            model.addElement((Filter)new PasoBajoFilter(intensidad));
        }
        jTextFieldIntensidad.setText("");

        updateFilters();
    }//GEN-LAST:event_jButtonAgregarActionPerformed

    private void jButtonEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEliminarActionPerformed
        if (jListFiltros.getSelectedIndex() == -1) {
            JOptionPane.showMessageDialog(this, "Debe seleccionar un filtro a eliminar", "Filtros", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        DefaultListModel model = (DefaultListModel) jListFiltros.getModel();
        model.remove(jListFiltros.getSelectedIndex());

        updateFilters();
    }//GEN-LAST:event_jButtonEliminarActionPerformed

    private void updateFilters() {

        loadImg.flush();
        BufferedImage orig = serv.openImage(ActualImage.getInstance().getPath());

        DefaultListModel model = (DefaultListModel) jListFiltros.getModel();

        Collection<Filter> filters = new ArrayList<Filter>();
        for (int i = 0; i < model.getSize(); i++) {
            filters.add((Filter)model.get(i));
        }

        BufferedImage filtered = serv.filterImage(orig, filters);
        ActualImage.getInstance().setFiltered(filtered);

        BufferedImage binar;
        if (filtered != null) {
            binar = serv.binarizeImage(filtered);
        } else {
            binar = serv.binarizeImage(orig);
        }
        ActualImage.getInstance().setBinarized(binar);

        refreshImages();
    }


    private void loadImage(ImagePlus newImage) {
        try {
            loadImg = newImage.getBufferedImage();
            
            ActualImage.getInstance().setBinarized(serv.binarizeImage(ActualImage.getInstance().getOriginal()));

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    private void showOriginalImg() {

        try {
            //BufferedImage loadImg = ImageIO.read(new File("Perfil3.jpg"));
            jPanelOriginal.setLocation(1, 1);
            int h = loadImg.getHeight();
            int w = loadImg.getWidth();

            jPanelOriginal.setSize(w, h);
            JImagePanel panel = new JImagePanel(loadImg, 0, 0, jPanelOriginal.getSize());

            jPanelOriginal.setLayout(new BorderLayout());
            panel.setVisible(true);
            jPanelOriginal.add(panel);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }



    private void showFilteredImg() {

        try {

            for (Component comp: jPanelFiltrada.getComponents()) {
                jPanelFiltrada.remove(comp);
            }

            if (ActualImage.getInstance().getFiltered() == null) {
                JPanel panel = new JPanel(null);

                jPanelFiltrada.setLayout(new BorderLayout());
                panel.setVisible(true);

                jPanelFiltrada.add(panel);
                return;
            }

            jPanelFiltrada.setLocation(1, 1);
            int h = loadImg.getHeight();
            int w = loadImg.getWidth();
            jPanelFiltrada.setSize(w, h);


   
            JImagePanel panel = new JImagePanel(ActualImage.getInstance().getFiltered(), 0, 0, jPanelFiltrada.getSize());

            jPanelFiltrada.setLayout(new BorderLayout());
            panel.setVisible(true);
            
            jPanelFiltrada.add(panel);
            
            
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void packFrame() {
        Component comp = this;
        while (!(comp instanceof JFrame)) {
            comp = comp.getParent();
        }
        ((JFrame)comp).validate();
    }


    private void showBinImg() {

        try {            

            jPanelBinarizada.setLocation(1, 1);

            int h = loadImg.getHeight();
            int w = loadImg.getWidth();

            jPanelBinarizada.setSize(w, h);

            for (Component comp: jPanelBinarizada.getComponents()) {
                jPanelBinarizada.remove(comp);
            }

            JImagePanel panel = new JImagePanel(ActualImage.getInstance().getBinarized(), 0, 0, jPanelBinarizada.getSize());

            jPanelBinarizada.setLayout(new BorderLayout());
            panel.setVisible(true);

            jPanelBinarizada.add(panel);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAgregar;
    private javax.swing.JButton jButtonEliminar;
    private javax.swing.JComboBox jComboBoxFiltro;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JList jListFiltros;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanelBinarizada;
    private javax.swing.JPanel jPanelFiltrada;
    private javax.swing.JPanel jPanelOriginal;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextFieldIntensidad;
    // End of variables declaration//GEN-END:variables

}
